﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MementoLibrary.DTOs;
using System.Net.Http;
using System.Configuration;
using Newtonsoft.Json;
using System.Net.Http.Headers;
using MementoLibrary;

namespace MementoClient.Classes
{
    internal class SubmitWorklogService
    {
        public void Submit(WorkLogDTO worklog, Action<WorklogSavedResult> callback)
        {
            var httpClient = Helpers.GetHttpClient();
            var url = ConfigurationManager.AppSettings["MementoServerUrl"] + "api/worklog";
            string content = JsonConvert.SerializeObject(worklog);
            var stringContent = new StringContent(content, Encoding.ASCII, MediaTypeHeaderValue.Parse("application/json").MediaType);
            var task = worklog.WorkLogId > 0 ? httpClient.PutAsync(url, stringContent) : httpClient.PostAsync(url, stringContent);
            task.ContinueWith(a =>
            {
                var response = a.Result.Content;
                response.ReadAsStringAsync().ContinueWith(b =>
                {
                    callback(JsonConvert.DeserializeObject<WorklogSavedResult>(b.Result));
                });
            });
        }
    }
}
